<?php defined('BASEPATH') or exit('No direct script access allowed');

class Expert_Expert_model extends CI_Model
{
     private $sid ;
     private $journey_table ;
     private $area_table ;
     public $admin_user_table ;
     private $expert_table ;
     private $expert_customer_table ;
     private $user_table ;


    public function __construct()
    {
        parent::__construct();
        $this->sid = $GLOBALS['sid'];
        $this->journey_table = $this->db->dbprefix('expert_journey');
        $this->area_table = $this->db->dbprefix('area');
        $this->admin_user_table = $this->db->dbprefix('admin_user');
        $this->expert_table = $this->db->dbprefix('expert');
        $this->expert_customer_table  = $this->db->dbprefix('expert_customer');
        $this->user_table  = $this->db->dbprefix('user');
        $this->expert_sharelog  = $this->db->dbprefix('expert_sharelog');
        $this->expert_viewlog  = $this->db->dbprefix('expert_viewlog');
    }

    public function expert_add($id)
    {
        return $this->db->insert($this->expert_table,array('id'=>$id, 'sid' => $this->sid));
    }

    public function check_exists_expert_by_id($id)
    {
        $query = $this->db->get_where($this->expert_table,array('id'=>$id), true);
        return $query->num_rows();
    }

    /**
     * 达人详细资料
     * @param $id  达人ID
     * @return array
     */

    public function _expert_info($id)
    {
        $t = $this->admin_user_table;
        $e = $this->expert_table;
        $this->db->select("*");
        $this->db->join($e,"$t.id = $e.id");
        $this->db->where(array("$t.id"=>$id));
        $query = $this->db->get($t,1);
        $res = $query->row_array();
        if($res){} $res['trips'] = $this->_expert_trips(array('user_id'=>$id),3,1);
        return $res ;
    }

    /**
     * 
     * 达人信息--手机
     * @param int $id
     */
    public function expert_info_m($id){   
        $t = $this->db->dbprefix('admin_user');
        $e = $this->db->dbprefix('expert');
        $condition = "" ;
        if(!empty($where)){

            foreach($where as $k=>$v)
            {
                $condition .= " AND $t.$k = $v ";
            }
        }
        $sql = "select $t.id,
                       $t.email,
                       $t.mobile,
                       $e.* from $t
                           left join
                           $e
                           on $t.id = $e.id
                   where $t.id = $id " ;
        $query = $this->db->query($sql);
        $row = $query->row_array();
        if($row['avatar'])$row['avatar'] = URLPRE.$row['avatar'];
        $row['company']  = $this->config->item('company','site');
        return $row;
    }
    
    public function expert_info_edit($id,$data=array()){
    	$table = $this->db->dbprefix('expert');
		$this->db->where(array('id'=>$id), NULL, FALSE);
		return $this->db->update($table,$data);
    }



    public function _expert_select($pid = 0)
    {
        $pid = intval($pid);
        $t = $this->db->dbprefix('admin_user');
        $e = $this->db->dbprefix('expert');
        $sid = $this->sid;
        $condition = "$t.is_open=1 and  $e.sid = $sid  and $t.name != '' and $e.pid=$pid" ;

        $sql = "select $t.*,$e.* from $e left join $t on $t.id = $e.id where  ".$condition." order by $t.add_time desc" ;
        $query = $this->db->query($sql);
        $res = $query->result_array();
        return $res ;
    }

    /**
     * 全部
     * @return array
     */

    public function _expert_list($where='',$extra='')
    {
        $t = $this->db->dbprefix('admin_user');
        $e = $this->db->dbprefix('expert');
        $sid = $this->sid;
        $condition = "$t.is_open=1 and  $e.sid = $sid  and $t.name != ''" ;
        if(!empty($where))
        {
           if(!empty($where['stars']))
           {
               $stars = $where['stars'] ;
               $condition .= " and $e.stars = $stars" ;
           }
           if(!empty($where['term']))
           {
                $term = $where['term'] ;
                $condition .= " and $e.term = $term" ;
           }
        }




        $sql = "select $t.*,$e.* from $e left join $t on $t.id = $e.id where  ".$condition." order by $t.add_time desc" ;
        $query = $this->db->query($sql);
        $res = $query->result_array();
        if($res)
        {
            foreach($res as $k=>$v)
            {
                $res[$k]['trips'] = $this->_expert_trips(array('user_id'=>$v['id']),2,1);
            }
        }
        return $res ;
    }

    public function _expert_trips(array $where = array(),$page_size = 10,$now_page = 1)
    {
        $t = $this->db->dbprefix('trips');
        $this->db->select('id,subject,abstract');
        $this->db->where($where);
        $query = $this->db->get($t,$page_size,($now_page-1)*$page_size);
        $res = $query->result_array();
        return $res ;
    }

    /**
     * 编辑达人
     * @param $data
     * @return true/false
     */
    public function _edit_expert($data,$where)
    {
        $t = $this->db->dbprefix('expert');
        if(!empty($where))
        {
            $this->db->select('id');
            $query = $this->db->get_where($t,$where,1);
            $res = $query->row_array();
            if($res)
            {
                $this->db->where($where);
                return $this->db->update($t,$data);
            }
            else
            {
                $data = array_merge($data,$where);
                return $this->db->insert($t, $data);
            }
        }
        return false;
    }

    /**
     *
     * 获取总数量
     * @param array $where 查询条件
     * 角色2 达人
     */
    public function get_expert_count($where=array(),$extra='')
    {
        $t = $this->expert_table ;
        $this->db->select('id');
        $this->db->from($t);
        if($extra)
        {
            $where['sid'] = $this->sid;
        }
        $this->db->where($where);
        return $this->db->count_all_results() ;
    }

    /**
     *
     * 获取推荐达人
     * @param array $where 查询条件
     * 角色2 达人
     */

    public function get_recommend_expert($limit='',$extra='')
    {
        $t = $this->admin_user_table;
        $e = $this->expert_table;
        $where = array($t.'.is_open'=>'1',$e.'.is_recommend'=>'1');
        if($extra)
        {
            $where["$e.sid"] = $this->sid;
        }

        $res = $this->_list($where,$limit,$now_page=1);
        return $res['list'] ;
    }

    public function _list(array $where = array(),$page_size=20,$now_page=1,$extra='', $searchkey = '')
    {
        $t = $this->admin_user_table ;
        $e = $this->expert_table ;
        $condition = "" ;
        if($extra)
        {
            $where["$e.sid"] = $this->sid;
        }

        if(!empty($where))
        {
            foreach($where as $k=>$v)
            {
                $v = addslashes($v);
                $condition .= " AND $k = '$v' ";
            }
        }

        if($searchkey){
            $condition .= " AND ($t.name LiKE '%$searchkey%' OR $t.mobile LIKE '%$searchkey%' OR $t.email LIKE '%$searchkey%')";
        }

        $condition .= " AND $t.name != ' '";
        $offset = ($now_page-1)*$page_size;
        $sql = "select * from $e  left join $t on $t.id = $e.id where 1 $condition ORDER BY views DESC,$e.id ASC limit $offset,$page_size" ;
        $query = $this->db->query($sql);
        $res = $query->result_array();
//        $count = $this->db->count_all_results();
        return array(
//            'count' => $count,
            'list'  => $res
        );
    }

    public function daren_list(array $names = array())
    {
        $rets = $ret = array();
        $t = $this->admin_user_table ;
        $e = $this->expert_table ;

        if(empty($names))
        {
            return array();
        }

        $condition = " $t.name  IN('".implode("', '", $names)."')";
        $sql = "select * from $e left join $t on $t.id = $e.id where $condition  " ;
        $query = $this->db->query($sql);
        $res = $query->result_array();
        foreach ($res as $k => $v) {
            $ret[$v['name']] = $v;
        }
        foreach ($names as $name) {
            $rets[$name] = $ret[$name];
        }

        return $rets;
    }




    /**
     *
     * 获取总数量
     * @param array $where 查询条件
     * 角色2 达人
     */
    public function get_customer_count($expert_id)
    {
        $t = $this->db->dbprefix('expert_customer');
        $this->db->select('user_id');
        $this->db->from($t);
        $this->db->where(array('expert_id'=>$expert_id));
        return $this->db->count_all_results() ;
    }


    /*
    **
    *
    * 获取所有客户
    * @param array $where 选择条件
    */
    public function get_customer_list($page_size=20,$now_page=1,$expert_id)
    {
        $limit  = $page_size ;
        $offset = ($now_page-1)*$page_size ;
        $t = $this->db->dbprefix('expert_customer');
        $e = $this->db->dbprefix('user');
        $sql = "select $e.user_id,$e.username,$e.email,$e.mobile,
                       $e.status,$e.reg_date,$e.login_date,$e.reg_ip,
                       $e.login_ip from $t left join $e on $t.user_id = $e.user_id
         where $e.status=1 and $t.expert_id=$expert_id limit $offset,$limit" ;
        $query = $this->db->query($sql);
        $res = $query->result_array();
        return $res ;

    }


    public function _edit_expert_status($data,$where)
    {
        $t = $this->db->dbprefix('admin_user');
        if(!empty($where))$this->db->where($where);
        return $this->db->update($t,$data);
        return false;

    }

    public function _edit_expert_recommend($data,$where)
    {
        $t = $this->db->dbprefix('expert');
        if(!empty($where))$this->db->where($where);
        return $this->db->update($t,$data);
        return false;

    }


    public function _expert_customer($user_id,$expert_id)
    {
        $t = $this->expert_customer_table;
        $where = array('user_id'=>$user_id,'expert_id'=>$expert_id);
        $this->db->where($where);
        $query = $this->db->get($t,1);
        $res = $query->row_array();
        if($res)
        {
            $check = TRUE ;
        }
        else
        {
         if($this->db->insert($t,$where))
         {
            $check = TRUE ;
         }
        }

        if($check)
        {
            return  array('status'=>'1','info'=>'操作成功','msg'=>'action_success');
        }

        return false;
    }


    /**
     *
     * 添加行程地区
     *
     */
    public function add_journey($data,$id)
    {
        if($data['continent']!=='-1') $param = $data['continent'] ;
        if($data['country']!=='-1') $param = $data['country'] ;
        if($data['province']!=='-1') $param = $data['province'] ;
        if($data['city']!=='-1') $param = $data['city'] ;
        $t = $this->journey_table;
        $array = array('area_id'=>$param,'user_id'=>$id,'sid'=>$data['sid']);
        $query = $this->db->get_where($t,$array,'1');
        if($query->row_array())
        {
            return false;
        }
        else
        {
            return $this->db->insert($t,$array);
        }
    }

    /**
     *
     * 删除达人
     * @param array $where 删除条件
     */
    public function _delete_expert($where=array()){
        if(!empty($where)&&is_array($where)){
            return $this->db->delete($this->expert_table,$where);
        }elseif(is_string($where)){
            $this->db->where($where, NULL, FALSE);
            return $this->db->delete($this->expert_table);
        }
        return false;
    }

    /**
     *
     * 删除达人行程
     * @param array $where 删除条件
     */
    public function _delete_journey($where=array()){
        $t = $this->journey_table;
        if(!empty($where)&&is_array($where)){
            return $this->db->delete($t,$where);
        }elseif(is_string($where)){
            $this->db->where($where);
            return $this->db->delete($t);
        }
        return false;
    }

    /**
     *
     * 获取达人行程总数量
     * @param array $where 查询条件
     *
     */
    public function get_journey_count($where=array())
    {
        $t = $this->journey_table ;
        $this->db->select('id');
        $this->db->from($t);
        $this->db->where($where);
        return $this->db->count_all_results() ;
    }


    /*
    **
    *
    * 获取所有达人行程
    * @param array $where 选择条件
    */
    public function get_journey_list($where=array(),$page_size=20,$now_page=1)
    {
        $t = $this->journey_table ;
        $e = $this->area_table ;
        $condition = "" ;
        if(isset($where['user_id'])&&!empty($where['user_id'])) $condition = $t.".user_id  = ". $where['user_id']  ;
        $this->db->select($t.'.id as jid');
        $this->db->select($e.'.name');
        $this->db->join($e,"$t.area_id = $e.id");
        $this->db->where($condition);
        $query = $this->db->get($t,$page_size,($now_page-1)*$page_size);

        $res = $query->result_array();
        return $res ;
    }


    public function db_update_views_share($admin_id, $views = 0, $share = 0){
        $this->db->where(array('id' => $admin_id, 'sid' => $GLOBALS['sid']));
        $this->db->set('views', 'views+'.$views, FALSE);
        $this->db->set('share', 'share+'.$share, FALSE);
        $ret = $this->db->update($this->expert_table);

        if($share){
            $this->db->insert($this->expert_sharelog, array(
                'uid' => $admin_id,
                'crts' => time(),
            ));
        }
        if($views){
            $this->db->insert($this->expert_viewlog, array(
                'uid' => $admin_id,
                'crts' => time(),
            ));
        }
        return $ret;
    }

    public function get_sharelog_count($uid)
    {
        $this->db->from($this->expert_sharelog);
        $this->db->where(array('uid'=> $uid));
        return $this->db->count_all_results();
    }

    public function get_sharelog_list($adminid,$page_size=20,$now_page=1){
        $t = $this->expert_sharelog;
        $condition = "uid =$adminid";
        $offset = ($now_page-1)*$page_size;

        $sql = "SELECT * FROM $t WHERE $condition ORDER BY crts DESC LIMIT $offset,$page_size" ;
        $query = $this->db->query($sql);
        $res = $query->result_array();
        return $res;
    }

    public function get_count_by_uid($uid, $type = '')
    {
        switch($type){
            case 'week':
                $weekago = strtotime(date('Y-m-d 00:00:00', strtotime("6 days ago")));
                $cd = " crts>=$weekago";
                break;
            case 'yesterday':
                $ago1 = strtotime(date('Y-m-d 00:00:00', strtotime("1 days ago")));
                $ago2 = strtotime(date('Y-m-d 00:00:00', strtotime("0 days ago")));
                $cd = " crts>=$ago1 AND crts<=$ago2";
                break;
            default:
                $weekago = strtotime(date('Y-m-d 00:00:00', strtotime("0 days ago")));
                $cd = " crts>=$weekago";
                break;
        }
        $sql = "SELECT COUNT(*) AS num FROM $this->expert_viewlog WHERE uid=$uid AND $cd";
        $query = $this->db->query($sql);
        $res = $query->result_array();
        return $res ? $res[0]['num'] : 0;
    }

    public function fetch_count_wmp($date_array)
    {
        foreach ($date_array as $k => $v) {
            $STARTv = strtotime($v . ' 00:00:01');
            $ENDV   = strtotime($v . ' 23:59:59');
            $sql = "SELECT COUNT(*) AS num FROM $this->expert_viewlog AS e,cs_admin_user AS a WHERE a.sid=" . SITEID . " AND a.id=e.uid AND e.crts>= $STARTv AND e.crts<=$ENDV";
            $query = $this->db->query($sql);
            $data = $query->result_array();
            $ret[$v] = $data[0]['num'];
        }
        return $ret;
    }

    public function fetch_share_count_wmp($date_array)
    {
        foreach ($date_array as $k => $v) {
            $STARTv = strtotime($v . ' 00:00:01');
            $ENDV   = strtotime($v . ' 23:59:59');
            $sql = "SELECT COUNT(*) AS num FROM $this->expert_sharelog AS e,cs_admin_user AS a WHERE a.sid=" . SITEID . " AND a.id=e.uid AND e.crts>= $STARTv AND e.crts<=$ENDV";
            $query = $this->db->query($sql);
            $data = $query->result_array();
            $ret[$v] = $data[0]['num'];
        }
        return $ret;
    }

}
